package com.maruti.otterapi.experts;

import com.maruti.otterapi.ListParameters;
import com.maruti.otterapi.Otter4JavaException;
import com.maruti.otterapi.TopsyConfig;
import com.maruti.otterapi.TopsyConstants;
import com.maruti.otterapi.TopsyInvoker;

public class Experts {

	private TopsyConfig topsyConfig;

	public TopsyConfig getTopsyConfig() {
		return topsyConfig;
	}

	public void setTopsyConfig(TopsyConfig topsyConfig) {
		this.topsyConfig = topsyConfig;
	}

	public ExpertsResponse experts(String query) throws Otter4JavaException {
		return fetchAll(query, 0);
	}

	public ExpertsResponse experts(String query, int config_NoFilters)
			throws Otter4JavaException {
		return fetchAll(query, config_NoFilters);
	}

	public ExpertsResponse experts(String query, ListParameters listParams)
			throws Otter4JavaException {
		return fetch(query, 0, listParams);
	}

	public ExpertsResponse experts(String query, int config_NoFilters,
			ListParameters listParams) throws Otter4JavaException {
		return fetch(query, config_NoFilters, listParams);
	}

	private ExpertsResponse fetchAll(String query, int config_NoFilters)
			throws Otter4JavaException {

		query = query.replaceAll("\\s", "%20");
		int page = 1;
		ListParameters listParameters = new ListParameters();
		listParameters.setPage("" + page);
		listParameters.setPerpage("100");

		ExpertsResponse response = fetch(query, config_NoFilters,
				listParameters);
		int total = Integer.parseInt(response.getResponse().getTotal());
		int fetcedRecs = response.getResponse().getList().size();
		ExpertsResponse response1 = null;
		String lastOffset = response.getResponse().getLast_offset();
		page++;
		while (total > fetcedRecs && page <= 10) {
			listParameters.setPage("" + page);
			//listParameters.setOffset(lastOffset);
			response1 = fetch(query, config_NoFilters, listParameters);
			response.getResponse().getList().addAll(
					response1.getResponse().getList());
			fetcedRecs += response1.getResponse().getList().size();
			System.out.println(response1.getResponse().getList().size());
			lastOffset = response1.getResponse().getLast_offset();
			page++;
		}

		return response;
	}

	private ExpertsResponse fetch(String query, int config_NoFilters,
			ListParameters listParams) throws Otter4JavaException {
		TopsyInvoker invoker = new TopsyInvoker();
		invoker.setTopsyConfig(topsyConfig);

		query = query.replaceAll("\\s", "%20");
		query += "&config_NoFilters=" + config_NoFilters;
		ExpertsResponse data = (ExpertsResponse) invoker.fetchData(
				TopsyConstants.expertsBaseURL + query + listParams.toQuery(),
				"experts");

		return data;
	}
}
